package com.example.paper.loginreg;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.example.db.DBManager;
import com.example.db.DaoSession;
import com.example.db.Goods;
import com.example.db.GoodsDao;
import com.example.mvp.model.BaseEntity;
import com.example.mvp.view.BaseActivity;
import com.example.paper.R;
import com.example.paper.api.Api;
import com.example.paper.brean.UpLoadBean;
import com.example.paper.http.factory.HttpFactory;
import com.example.paper.http.factory.HttpType;
import com.example.paper.mvp.contract.LoginContract;
import com.example.paper.mvp.model.LoginModel;
import com.example.paper.mvp.presenter.LoginPresenter;
import com.example.paper.mvp.view.AllActivity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ChangeActivity extends BaseActivity<LoginPresenter> implements LoginContract.LoginView {

    private RelativeLayout imgSelect;
    private RelativeLayout nicknameName;
    private TextView usernameMsd;
    private ImageView backUp;
    private String path;
    private ImageView titleImageShow;
    private getUserBroadcast getUserBroadcast;
    private RelativeLayout sex_select;
    private TextView text_sex;

    @Override
    public View addStatusView() {
        return null;
    }

    public void upLoads(String path) {
        mPresenter.RequestUpload(path);
//        File file = new File(path);
//        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        MultipartBody.Builder builder = new MultipartBody.Builder();
//        builder.addFormDataPart("file","jhy"+System.currentTimeMillis()+".jpg",requestFile);
//        List<MultipartBody.Part> list = builder.build().parts();
//
//        HttpFactory.getInstance().factory(HttpType.TOKENSIGNTYPE)
//                .getRetrofit()
//                .create(Api.class)
//                .requestUpload(list)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<UpLoadBean>() {
//                    @Override
//                    public void onSubscribe(@NonNull Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(@NonNull UpLoadBean upLoadBean) {
//                        if (upLoadBean.getStatuesCode().equals("200")){
//                            Toast.makeText(getApplication(), ""+upLoadBean.getMsg(), Toast.LENGTH_SHORT).show();
//                        }
//                    }
//
//                    @Override
//                    public void onError(@NonNull Throwable e) {
//                        Log.e("asd",""+e.getMessage());
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
    }

    //返回值判断
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == Activity.RESULT_OK) {
            Glide.with(this).load(path).circleCrop().into(titleImageShow);
            //上传头像
            upLoads(path);
            //存入数据库
            List<Goods> goods = DBManager.getDbManager().getDaoSession().loadAll(Goods.class);
            for (Goods good : goods) {
                //修改用户的头像
                good.setUser_img(path);
                DBManager.getDbManager().getDaoSession().update(good);
                Glide.with(this).load(good.getUser_img()).circleCrop().into(titleImageShow);
            }

        } else if (requestCode == 102 && resultCode == Activity.RESULT_OK) {
            Uri data1 = data.getData();
            Glide.with(this).load(data1).circleCrop().into(titleImageShow);
            //上传头像
            upLoads(data1.toString());
        }
    }

    @Override
    public void refresh(BaseEntity baseEntity) {
        if (baseEntity instanceof UpLoadBean) {
            UpLoadBean baseEntity1 = (UpLoadBean) baseEntity;
            if (baseEntity1.getStatuesCode().equals("200")) {
                Toast.makeText(this, "头像上传成功", Toast.LENGTH_SHORT).show();

            } else {
                Log.e("asd", "" + baseEntity1.getMsg());
            }
        } else {
            if (baseEntity.getStatus().equals("200")) {
                Log.e("asd", "用户修改成功");
            }
        }
    }


    //广播接收者
    class getUserBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //判断地址值是否相等
            if (intent.getAction().equals("sends_user_name")) {
                String send_userName = intent.getStringExtra("send_userName");
                //赋值
                usernameMsd.setText("" + send_userName);

                //修改名字
                DaoSession daoSession = DBManager.getDbManager().getDaoSession();
                //查询全部
                List<Goods> goods = daoSession.loadAll(Goods.class);
                for (Goods good : goods) {
                    //为true 正在登陆
                    if (good.getLogin()) {
                        good.setUser_name(send_userName);
                        //修改   查找到的
                        daoSession.update(good);
                    }
                }

//                修改之后查询全部
//                List<Goods> goods1 = daoSession.loadAll(Goods.class);
//                LogUtils.json(goods1);

            }
        }

    }

    @Override
    protected void onDestroy() {
        //解广播
        unregisterReceiver(getUserBroadcast);

        //正在登陆的用户信息
        Goods unique = DBManager.getDbManager().getDaoSession().queryBuilder(Goods.class)
                .where(GoodsDao.Properties.Login.eq(true)).unique();

        int user_id = Integer.parseInt(unique.getUser_id());
        String user_img = unique.getUser_img();
        int user_integral = 1;
        String user_name = unique.getUser_name();
        int user_phone = unique.getUser_phone();
        String user_pwd = unique.getUser_pwd();
        String user_sex = unique.getUser_sex();
        Log.e("asd", "user_id:" + user_id + "--user_img:" + user_img + "--user_integral:" + user_integral + "--user_name:" + user_name + "--user_phone:" + user_phone + "--user_pwd:" + user_pwd + "--user_sex:" + user_sex);

        if (user_sex.equals("男") || user_sex.equals("保密")) {
            user_sex = "0";
        }
        if (user_sex.equals("女")) {
            user_sex = "1";
        }

        Map<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("user_img", user_img);
        map.put("user_integral", user_integral);
        map.put("user_name", user_name);
        map.put("user_phone", user_phone);
        map.put("user_pwd", user_pwd);
        map.put("user_sex", user_sex);
        mPresenter.RequestUpdate(map);

        super.onDestroy();
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_change;
    }

    public void initView() {
        imgSelect = (RelativeLayout) findViewById(R.id.img_select);
        nicknameName = (RelativeLayout) findViewById(R.id.nickname_name);
        sex_select = (RelativeLayout) findViewById(R.id.sex_select);
        usernameMsd = (TextView) findViewById(R.id.username_msd);
        text_sex = (TextView) findViewById(R.id.text_sex);
        backUp = (ImageView) findViewById(R.id.back_up);
        titleImageShow = (ImageView) findViewById(R.id.title_image_show);

    }

    @Override
    public void initData() {
        mPresenter = new LoginPresenter(new LoginModel(), this);
        //注册广播
        getUserBroadcast = new getUserBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        //注册地址值
        intentFilter.addAction("sends_user_name");
        registerReceiver(getUserBroadcast, intentFilter);


        //男女设置
        sex_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupWindow popupWindow = new PopupWindow();
                View inflate = LayoutInflater.from(ChangeActivity.this).inflate(R.layout.pop_sex_select, null);

                //获取id
                Button male_btn = inflate.findViewById(R.id.male_btn);
                Button female_btn = inflate.findViewById(R.id.female_btn);
                Button no_btn_sex = inflate.findViewById(R.id.no_btn_sex);

                //性别男
                male_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        List<Goods> list = DBManager.getDbManager().getDaoSession().queryBuilder(Goods.class)
                                .where(GoodsDao.Properties.Login.eq(true)).list();
                        for (Goods goods : list) {
                            goods.setUser_sex("0");
                            DBManager.getDbManager().getDaoSession().update(goods);
                        }
                        text_sex.setText("男");
                    }
                });

                //性别女
                female_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        List<Goods> list = DBManager.getDbManager().getDaoSession().queryBuilder(Goods.class)
                                .where(GoodsDao.Properties.Login.eq(true)).list();
                        for (Goods goods : list) {
                            goods.setUser_sex("1");
                            DBManager.getDbManager().getDaoSession().update(goods);
                        }
                        text_sex.setText("女");
                    }
                });

                //取消
                no_btn_sex.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });

                popupWindow.setFocusable(true);
                popupWindow.setContentView(inflate);
                //设置宽高
                popupWindow.setHeight(ViewPager.LayoutParams.WRAP_CONTENT);
                popupWindow.setWidth(ViewPager.LayoutParams.MATCH_PARENT);
                //显示
                popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            }
        });

        //头像更新
        imgSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupWindow popupWindow = new PopupWindow();
                //加载布局
                View inflate = LayoutInflater.from(ChangeActivity.this).inflate(R.layout.pop_title_image, null);
                Button take_pictures_btn = inflate.findViewById(R.id.take_pictures_btn);
                Button gallery_btn = inflate.findViewById(R.id.gallery_btn);
                Button no_btn = inflate.findViewById(R.id.no_btn);
                popupWindow.setFocusable(true);

                //拍照
                take_pictures_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent();
                        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                        path = "/sdcard/DCIM/Camera/" + System.currentTimeMillis() + ".jpg";
                        Uri uriForFile = FileProvider.getUriForFile(ChangeActivity.this,
                                "com.example.paper",
                                new File(path));
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile);
                        startActivityForResult(intent, 101);
                        popupWindow.dismiss();

                    }
                });

                //相册
                gallery_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, 102);
                        popupWindow.dismiss();

                    }
                });

                //取消
                no_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });

                popupWindow.setContentView(inflate);
                //设置宽高
                popupWindow.setHeight(ViewPager.LayoutParams.WRAP_CONTENT);
                popupWindow.setWidth(ViewPager.LayoutParams.MATCH_PARENT);
                //显示
                popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

            }
        });


        //退出
        backUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转
                startPage(AllActivity.class);
                finish();
            }
        });

        //跳转下一个页面
        nicknameName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转修改用户名详情
                Intent intent = new Intent(ChangeActivity.this, ChangeNameActivity.class);
                startActivity(intent);
            }
        });

        //修改名字  更新后的数据库然后再修改复制
        List<Goods> goods = DBManager.getDbManager().getDaoSession().loadAll(Goods.class);
        for (Goods good : goods) {
            usernameMsd.setText("" + good.getUser_name());
            if (!good.getUser_img().equals("")) {
                Glide.with(ChangeActivity.this).load(good.getUser_img()).circleCrop().into(titleImageShow);
            }
            if (good.getUser_sex().equals("0")){
                text_sex.setText("男");
            }else if (good.getUser_sex().equals("1")){
                text_sex.setText("女");
            }
        }
        //查询
        LogUtils.json(goods);

    }
}